import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_detail/widgets/test_card_base.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:math' as math;

class TestMatchingResultBlock extends StatelessWidget {
  final Map? componentsData;

  const TestMatchingResultBlock({super.key, this.componentsData});

  @override
  Widget build(BuildContext context) {
    return TestCardBase(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 圆形装饰和头像部分
          _buildAvatarDecoration(),

          // SizedBox(height: 24.w),

          // 渐变卡片部分
          SizedBox(
            // color: Colors.red,
            width: double.infinity,
            child: Stack(
              children: [
                Positioned(child: _buildCardWithGradient()),
                Positioned(
                  left: 32.w,
                  top: 0,
                  child: _buildCircleWithBookIcon(),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  // 创建圆形头像与装饰
  Widget _buildAvatarDecoration() {
    return Stack(
      alignment: Alignment.center,
      children: [
        // 最外层六边形轮廓
        CustomPaint(
          size: Size(190.w, 190.w),
          painter: HexagonBorderPainter(
            borderColor: AppColor.colorE4EBF0,
            strokeWidth: 1.6.w,
          ),
        ),

        // 中层六边形轮廓
        CustomPaint(
          size: Size(140.w, 140.w),
          painter: HexagonBorderPainter(
            borderColor: AppColor.colorE4EBF0,
            strokeWidth: 1.2.w,
          ),
        ),

        // 中心六边形头像容器
        SizedBox(
          width: 90.w,
          height: 90.w,
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 六边形渐变背景
              CustomPaint(
                size: Size(90.w, 90.w),
                painter: HexagonGradientPainter(
                  gradient: const LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFFB8F7FF),
                      Colors.white,
                    ],
                  ),
                  fillColor: Colors.white,
                ),
              ),

              // 头像图片
              Positioned(
                top: 10.w,
                left: 10.w,
                right: 10.w,
                bottom: 10.w,
                child: AutoImage(
                  Assets.innovativeLeader,
                  width: 70.w,
                  height: 70.w,
                ),
              ),
            ],
          ),
        ),

        // 左下熊图标
        Positioned(
          bottom: 30.w,
          left: 30.w,
          child: _buildAnimalCircle(Assets.testBear),
        ),

        // 右上兔子图标
        Positioned(
          top: 18.w,
          right: 18.w,
          child: _buildAnimalCircle(Assets.testRabbit),
        ),
      ],
    );
  }

  // 创建动物图标圆圈
  Widget _buildAnimalCircle(String imageAsset) {
    return Container(
      width: 32.w,
      height: 32.w,
      decoration: const BoxDecoration(
        color: AppColor.colorE4EBF0,
        shape: BoxShape.circle,
      ),
      child: Center(
        child: AutoImage(
          imageAsset,
          width: 24.w,
          height: 24.w,
        ),
      ),
    );
  }

  // 创建带渐变背景的卡片
  Widget _buildCardWithGradient() {
    Map data = componentsData ??
        {
          "result_type": "Personality Type",
          "result_value": "ENFP",
          "result_title": "Innovative Leader",
          "result_desc":
              "You have strong innovative spirit and leadership potential, are good at guiding the team, and keep an open mind to accept new ideas and challenges.",
          "result_image": "url"
        };
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 22.w),
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            AppColor.colorF5F5F5.withOpacity(1.0),
            AppColor.colorF5F5F5.withOpacity(0.0),
          ],
        ),
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: Column(
        children: [
          // 蓝色圆形与图标

          // SizedBox(height: 8.w),

          // 标题文字
          Text(
            data['result_title'] ?? '',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: AppColor.color0C0A09,
            ),
            textAlign: TextAlign.center,
          ),

          SizedBox(height: 8.w),

          // 描述文字
          Text(
            data['result_desc'] ?? '',
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColor.color7F909E,
              height: 1.26,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  // 创建带有书籍图标的蓝色圆圈
  Widget _buildCircleWithBookIcon() {
    return Container(
      width: 44.w,
      height: 44.w,
      decoration: const BoxDecoration(
        color: AppColor.primary,
        shape: BoxShape.circle,
      ),
      child: Center(
          child: AutoImage(
        Assets.testCardBook,
        width: 24.w,
      )),
    );
  }
}

// 基础六边形路径生成器（抽象类）
abstract class BaseHexagonPainter extends CustomPainter {
  final double strokeWidth;

  BaseHexagonPainter({
    this.strokeWidth = 1.0,
  });

  Path _createRoundedHexagonPath(Size size) {
    final path = Path();
    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width / 2 - strokeWidth / 2;

    // 圆角半径 - 根据六边形大小适当调整
    final cornerRadius = size.width / 12;

    List<Offset> vertices = [];
    for (int i = 0; i < 6; i++) {
      final angle = (i * 60 - 30) * (math.pi / 180);
      final x = centerX + radius * math.cos(angle);
      final y = centerY + radius * math.sin(angle);
      vertices.add(Offset(x, y));
    }

    // 使用更简单的方法创建圆角六边形
    // 准备控制点数组
    List<Offset> controlPoints = [];

    // 计算每个角的控制点
    for (int i = 0; i < 6; i++) {
      // 获取当前顶点和下一个顶点
      Offset current = vertices[i];
      Offset next = vertices[(i + 1) % 6];

      // 沿着边的方向向量
      double edgeDx = next.dx - current.dx;
      double edgeDy = next.dy - current.dy;
      double edgeDistance = math.sqrt(edgeDx * edgeDx + edgeDy * edgeDy);
      double edgeUnitX = edgeDx / edgeDistance;
      double edgeUnitY = edgeDy / edgeDistance;

      // 计算从当前顶点出发的控制点
      Offset startPoint = Offset(current.dx + edgeUnitX * cornerRadius,
          current.dy + edgeUnitY * cornerRadius);

      // 添加控制点
      controlPoints.add(startPoint);
    }

    // 开始绘制路径
    if (controlPoints.isNotEmpty) {
      path.moveTo(controlPoints[0].dx, controlPoints[0].dy);
    }

    // 绘制每条边和圆角
    for (int i = 0; i < 6; i++) {
      Offset currentVertex = vertices[i];
      Offset nextVertex = vertices[(i + 1) % 6];

      // 获取对应的控制点
      Offset currentControl = controlPoints[i];
      Offset nextControl = controlPoints[(i + 1) % 6];

      // 绘制当前控制点到下一个控制点的直线段
      // 计算当前边的结束点（下一个顶点之前的控制点）
      double edgeDx = nextVertex.dx - currentVertex.dx;
      double edgeDy = nextVertex.dy - currentVertex.dy;
      double edgeDistance = math.sqrt(edgeDx * edgeDx + edgeDy * edgeDy);
      double edgeUnitX = edgeDx / edgeDistance;
      double edgeUnitY = edgeDy / edgeDistance;

      Offset endPoint = Offset(nextVertex.dx - edgeUnitX * cornerRadius,
          nextVertex.dy - edgeUnitY * cornerRadius);

      // 绘制直线段
      path.lineTo(endPoint.dx, endPoint.dy);

      // 绘制圆角到下一个控制点
      path.quadraticBezierTo(
          nextVertex.dx, nextVertex.dy, nextControl.dx, nextControl.dy);
    }

    path.close();
    return path;
  }
}

// 六边形边框绘制器
class HexagonBorderPainter extends BaseHexagonPainter {
  final Color borderColor;

  HexagonBorderPainter({
    required this.borderColor,
    super.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Path path = _createRoundedHexagonPath(size);

    // 绘制边框
    final Paint borderPaint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth;

    canvas.drawPath(path, borderPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    if (oldDelegate is HexagonBorderPainter) {
      return oldDelegate.borderColor != borderColor ||
          oldDelegate.strokeWidth != strokeWidth;
    }
    return true;
  }
}

// 六边形渐变填充绘制器
class HexagonGradientPainter extends BaseHexagonPainter {
  final Gradient? gradient;
  final Color? fillColor;

  HexagonGradientPainter({
    this.gradient,
    this.fillColor,
    super.strokeWidth = 1.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Path path = _createRoundedHexagonPath(size);

    // 绘制填充
    final Paint fillPaint = Paint()..style = PaintingStyle.fill;

    if (gradient != null) {
      fillPaint.shader =
          gradient!.createShader(Rect.fromLTWH(0, 0, size.width, size.height));
    } else if (fillColor != null) {
      fillPaint.color = fillColor!;
    } else {
      // 默认的渐变填充
      fillPaint.shader = LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [
          Color(0xFFB8F7FF),
          Colors.white,
        ],
      ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
    }

    canvas.drawPath(path, fillPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
